import dashscope,json
from django.conf import settings
from django.http import HttpResponse
from dashscope.audio.tts_v2 import VoiceEnrollmentService, SpeechSynthesizer

dashscope.api_key = settings.ALIYUN_KEY
#指定用于语音合成的模型名
model = "cosyvoice-clone-v1"

#指定用于语音合成的音色名
#voice = "cosyvoice-prefix-e52c282238e841cca9ac304d36977392" #林
#voice = "cosyvoice-002-ae19972144b9415594ab7a78d9332748" #汪
voice = 'longjielidou'

#volume:合成音频的音量，取值范围：0~100。

#speech_rate
'''
合成音频的语速，取值范围：0.5~2。
0.5：表示默认语速的0.5倍速。
1：表示默认语速。默认语速是指模型默认输出的合成语速，语速会依据每一个发音人略有不同，约每秒钟4个字。
2：表示默认语速的2倍速。
'''

#pitch_rate 合成音频的语调，取值范围：0.5~2。

def yibu(req):
    try:
        synthesizer = SpeechSynthesizer(model=model, voice=voice)
        audio = synthesizer.call(req.GET.get('text'))
        # 将合成的音频文件保存到本地文件
        with open("output.mp3", "wb") as f:
            f.write(audio)
        return HttpResponse(synthesizer.get_last_request_id())
    except Exception as e:
        return HttpResponse(json.dumps({'code': 1, 'msg': f"{e}"}))

def list(req):
    service = VoiceEnrollmentService()
    voice_list = service.list_voices()
    return HttpResponse(voice_list)
